<template>
  <div class="theater-preview-app">
    <div class="container">
      <!-- 顶部导航 -->
      <header class="top-nav">
        <div class="nav-left">
          <button class="back-btn" @click="goBack">
            <span class="icon-arrow-left">←</span>
          </button>
          <h1 class="page-title">剧场预览</h1>
        </div>
        <div class="nav-right">
          <button class="btn btn-secondary" @click="editTheater">
            <span class="icon-edit">✏️</span>
            编辑剧场
          </button>
          <button class="btn btn-primary" @click="startExperience">
            <span class="icon-play">▶️</span>
            开始体验
          </button>
        </div>
      </header>

      <!-- 🔧 优化后的横幅区域 -->
      <div class="banner">
        <div class="banner-content">
          <div class="banner-main">
            <div class="banner-info">
              <h2 class="theater-title">{{ theaterData.title || '未命名剧场' }}</h2>
              <p class="theater-description">{{ theaterData.description || '暂无描述' }}</p>

              <div class="meta-badges">
                <span class="meta-badge era-badge">
                  <span class="badge-icon">🕐</span>
                  {{ theaterData.era || '未设定' }}
                </span>
                <span class="meta-badge location-badge">
                  <span class="badge-icon">📍</span>
                  {{ theaterData.location || '未设定' }}
                </span>
                <span class="meta-badge author-badge">
                  <span class="badge-icon">👤</span>
                  {{ theaterData.author || 'AI智能生成器' }}
                </span>
              </div>
            </div>

            <div class="banner-stats">
              <div class="stat-mini">
                <span class="stat-mini-value">{{ plotNodes.length }}</span>
                <span class="stat-mini-label">剧情</span>
              </div>
              <div class="stat-mini">
                <span class="stat-mini-value">{{ characters.length }}</span>
                <span class="stat-mini-label">角色</span>
              </div>
              <div class="stat-mini">
                <span class="stat-mini-value">{{ getTotalDuration() }}分</span>
                <span class="stat-mini-label">时长</span>
              </div>
            </div>
          </div>

          <div class="banner-actions">
            <button class="action-btn primary" @click="startExperience">
              <span class="btn-icon">▶️</span>
              开始体验
            </button>
            <button
              class="action-btn secondary"
              @click="shareTheater"
              :class="{ loading: isSharing }"
            >
              <span class="btn-icon" v-if="!isSharing">📤</span>
              <span class="spinner" v-else>⏳</span>
              {{ isSharing ? '分享中...' : '分享' }}
            </button>
            <button
              class="icon-action-btn"
              @click="toggleBookmark"
              :class="{ bookmarked: isBookmarked }"
            >
              {{ isBookmarked ? '🔖' : '📑' }}
            </button>
          </div>
        </div>

        <!-- 装饰效果 -->
        <div class="banner-decoration">
          <div class="decoration-orb orb-1"></div>
          <div class="decoration-orb orb-2"></div>
          <div class="decoration-orb orb-3"></div>
        </div>
      </div>

      <!-- 剧情导航区 -->
      <div class="story-navigation" v-if="plotNodes.length > 0">
        <div class="nav-header">
          <h3 class="nav-title">
            <span class="icon-route">🛤️</span>
            剧情流程导航
          </h3>
          <div class="progress-info">
            <span class="current-node">{{ currentNodeInfo.title || '选择一个节点' }}</span>
            <span class="progress-text">{{ currentNodeIndex + 1 }} / {{ plotNodes.length }}</span>
          </div>
        </div>

        <div class="story-timeline">
          <div class="timeline-navigation">
            <button
              class="timeline-nav-btn"
              @click="scrollTimeline('left')"
              :disabled="timelineScrollLeft <= 0"
            >
              <span>◀</span>
            </button>
            <button
              class="timeline-nav-btn"
              @click="scrollTimeline('right')"
              :disabled="timelineScrollLeft >= maxScrollLeft"
            >
              <span>▶</span>
            </button>
          </div>

          <div class="timeline-track" ref="timelineTrack" @scroll="updateScrollPosition">
            <div
              v-for="(node, index) in plotNodes"
              :key="node.id"
              class="timeline-node"
              :class="{
                active: index === currentNodeIndex,
                completed: index < currentNodeIndex,
                upcoming: index > currentNodeIndex,
              }"
              @click="selectNode(index)"
            >
              <div class="node-marker">
                <div class="node-dot">
                  <span v-if="index < currentNodeIndex" class="check-icon">✓</span>
                  <span v-else-if="index === currentNodeIndex" class="play-icon">▶</span>
                  <span v-else class="node-number">{{ index + 1 }}</span>
                </div>
                <div class="node-type" v-if="getNodeType(node)">
                  <span>{{ getNodeTypeIcon(node) }}</span>
                </div>
              </div>

              <div class="node-content">
                <div class="node-header">
                  <h4 class="node-title">{{ node.title }}</h4>
                  <div class="node-participants">
                    <div
                      v-for="charId in getNodeParticipants(node.id)"
                      :key="charId"
                      class="participant-avatar"
                      :title="getCharacterName(charId)"
                    >
                      <img :src="getCharacterAvatar(charId)" :alt="getCharacterName(charId)" />
                    </div>
                  </div>
                </div>
                <p class="node-description">{{ getNodeDescription(node) }}</p>

                <div class="node-features">
                  <span
                    v-for="feature in getNodeFeatures(node).slice(0, 2)"
                    :key="feature"
                    class="feature-badge"
                  >
                    {{ feature }}
                  </span>
                  <span v-if="getNodeFeatures(node).length > 2" class="feature-more">
                    +{{ getNodeFeatures(node).length - 2 }}
                  </span>
                </div>

                <div class="node-meta">
                  <span class="node-duration">
                    <span class="icon-duration">⏱️</span>
                    {{ getNodeDuration(node) }}分钟
                  </span>
                  <span class="node-difficulty" :class="getNodeDifficulty(node).class">
                    <span>{{ getNodeDifficulty(node).icon }}</span>
                    {{ getNodeDifficulty(node).label }}
                  </span>
                </div>
              </div>

              <div class="node-connector" v-if="index < plotNodes.length - 1"></div>
            </div>
          </div>

          <div class="timeline-progress">
            <div
              class="progress-bar"
              :style="{ width: `${((currentNodeIndex + 1) / plotNodes.length) * 100}%` }"
            ></div>
          </div>
        </div>
      </div>

      <!-- 🔧 优化后的内容区域 -->
      <div class="unified-content">
        <!-- 标签页导航 -->
        <div class="content-tabs">
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'plot' }"
            @click="switchTab('plot')"
          >
            <span class="tab-icon">📚</span>
            <span>剧情概览</span>
            <div class="tab-indicator" v-if="activeTab === 'plot'"></div>
          </button>
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'character' }"
            @click="switchTab('character')"
          >
            <span class="tab-icon">👥</span>
            <span>角色状态</span>
            <div class="tab-indicator" v-if="activeTab === 'character'"></div>
          </button>
          <button
            class="tab-btn"
            :class="{ active: activeTab === 'settings' }"
            @click="switchTab('settings')"
          >
            <span class="tab-icon">⚙️</span>
            <span>剧场设置</span>
            <div class="tab-indicator" v-if="activeTab === 'settings'"></div>
          </button>
        </div>

        <div class="tab-content">
          <!-- 🔧 优化后的剧情概览标签页 -->
          <div v-show="activeTab === 'plot'" class="tab-panel plot-panel">
            <div class="panel-header-compact">
              <div class="header-left">
                <h3 class="panel-title-compact">{{ currentNodeInfo.title || '选择一个节点' }}</h3>
                <div class="node-status-compact">
                  <span
                    class="status-badge-compact"
                    :class="currentNodeIndex < plotNodes.length - 1 ? 'in-progress' : 'completed'"
                  >
                    <span>{{ currentNodeIndex < plotNodes.length - 1 ? '▶️' : '✅' }}</span>
                    {{ currentNodeIndex < plotNodes.length - 1 ? '待体验' : '完整剧情' }}
                  </span>
                </div>
              </div>
              <div class="header-actions">
                <button class="action-btn-mini" @click="previewNode" title="预览此节点">👁️</button>
                <button class="action-btn-mini" @click="exportNode" title="导出此节点">💾</button>
              </div>
            </div>

            <!-- 紧凑的内容卡片网格 -->
            <div class="content-grid">
              <!-- 节点内容卡片 -->
              <div class="content-card" v-if="currentNodeInfo.content">
                <div class="card-header">
                  <h4 class="card-title">
                    <span class="icon">📜</span>
                    节点内容
                  </h4>
                  <button class="expand-toggle" @click="toggleSummaryExpanded">
                    {{ summaryExpanded ? '▲' : '▼' }}
                  </button>
                </div>
                <div class="card-body" :class="{ expanded: summaryExpanded }">
                  <div class="content-preview" v-html="currentNodeInfo.content"></div>
                  <div v-if="summaryExpanded" class="content-details">
                    <div class="detail-row">
                      <span class="detail-label">预计时长：</span>
                      <span class="detail-value">{{ getNodeDuration(currentNodeInfo) }}分钟</span>
                    </div>
                    <div class="detail-row">
                      <span class="detail-label">参与角色：</span>
                      <span class="detail-value"
                        >{{ getNodeParticipants(currentNodeInfo.id).length }}位</span
                      >
                    </div>
                  </div>
                </div>
              </div>

              <!-- 节点特征卡片 -->
              <div class="content-card">
                <div class="card-header">
                  <h4 class="card-title">
                    <span class="icon">🏷️</span>
                    节点特征
                  </h4>
                </div>
                <div class="card-body">
                  <div class="feature-tags-compact">
                    <span
                      v-for="feature in getNodeFeatures(currentNodeInfo)"
                      :key="feature"
                      class="feature-tag-compact"
                      @click="filterByFeature(feature)"
                    >
                      {{ feature }}
                    </span>
                  </div>
                </div>
              </div>

              <!-- 角色设置卡片 -->
              <div class="content-card wide" v-if="getCurrentNodeCharacterSettings().length > 0">
                <div class="card-header">
                  <h4 class="card-title">
                    <span class="icon">👥</span>
                    角色设置
                    <span class="count-badge">{{ getCurrentNodeCharacterSettings().length }}</span>
                  </h4>
                </div>
                <div class="card-body">
                  <div class="character-settings-compact">
                    <div
                      v-for="setting in getCurrentNodeCharacterSettings()"
                      :key="setting.characterId"
                      class="character-setting-mini"
                    >
                      <div class="setting-avatar">
                        <img :src="setting.avatar" :alt="setting.name" />
                      </div>
                      <div class="setting-info">
                        <span class="setting-name">{{ setting.name }}</span>
                        <div
                          class="setting-behaviors"
                          v-if="setting.behaviors && setting.behaviors.length > 0"
                        >
                          <span
                            v-for="behavior in setting.behaviors.slice(0, 2)"
                            :key="behavior"
                            class="behavior-mini"
                          >
                            {{ behavior }}
                          </span>
                          <span v-if="setting.behaviors.length > 2" class="more-behaviors">
                            +{{ setting.behaviors.length - 2 }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 🔧 优化后的角色状态标签页 -->
          <div v-show="activeTab === 'character'" class="tab-panel character-panel">
            <div class="panel-header-compact">
              <div class="header-left">
                <h3 class="panel-title-compact">角色详情</h3>
              </div>
              <div class="character-controls-compact">
                <div class="character-nav">
                  <button
                    class="nav-btn"
                    @click="prevCharacter"
                    :disabled="currentCharacterIndex === 0"
                  >
                    ◀
                  </button>
                  <span class="nav-info">
                    {{ currentCharacterIndex + 1 }} / {{ filteredCharacters.length }}
                  </span>
                  <button
                    class="nav-btn"
                    @click="nextCharacter"
                    :disabled="currentCharacterIndex === filteredCharacters.length - 1"
                  >
                    ▶
                  </button>
                </div>
                <select v-model="characterFilter" @change="filterCharacters" class="filter-select">
                  <option value="all">所有角色</option>
                  <option value="main">主要角色</option>
                  <option value="support">辅助角色</option>
                </select>
              </div>
            </div>

            <!-- 紧凑的角色信息 -->
            <div class="character-content" v-if="currentCharacter">
              <!-- 角色基本信息卡片 -->
              <div class="character-card-compact">
                <div class="character-main">
                  <div class="character-avatar-section">
                    <img
                      :src="currentCharacter.avatar"
                      :alt="currentCharacter.name"
                      class="character-avatar"
                    />
                    <div class="character-status">⭐</div>
                  </div>
                  <div class="character-info">
                    <h4 class="character-name">{{ currentCharacter.name }}</h4>
                    <p class="character-role">主要角色</p>
                    <div class="character-desc" :class="{ expanded: charDescExpanded }">
                      <p>{{ currentCharacter.description }}</p>
                      <button class="desc-toggle" @click="charDescExpanded = !charDescExpanded">
                        {{ charDescExpanded ? '收起 ▲' : '展开 ▼' }}
                      </button>
                    </div>
                  </div>
                </div>

                <!-- 角色导航指示器 -->
                <div class="character-indicators-compact">
                  <div
                    v-for="(character, index) in filteredCharacters.slice(0, 5)"
                    :key="character.id"
                    class="char-indicator-mini"
                    :class="{ active: index === currentCharacterIndex }"
                    @click="goToCharacter(index)"
                  >
                    <img :src="character.avatar" :alt="character.name" />
                  </div>
                  <span v-if="filteredCharacters.length > 5" class="more-chars">
                    +{{ filteredCharacters.length - 5 }}
                  </span>
                </div>
              </div>

              <!-- 角色详细信息网格 -->
              <div class="character-details-grid">
                <!-- 技能卡片 -->
                <div class="detail-card" v-if="getCharacterSkills(currentCharacter).length > 0">
                  <div class="detail-card-header">
                    <span class="detail-icon">🎯</span>
                    <h5 class="detail-title">拥有技能</h5>
                    <span
                      v-if="getCharacterSkillCategory(currentCharacter)"
                      class="skill-category-mini"
                    >
                      {{ getCharacterSkillCategory(currentCharacter) }}
                    </span>
                  </div>
                  <div class="detail-card-body">
                    <div class="skills-compact">
                      <span
                        v-for="skill in getCharacterSkills(currentCharacter).slice(0, 6)"
                        :key="skill"
                        class="skill-mini"
                      >
                        {{ skill }}
                      </span>
                      <span
                        v-if="getCharacterSkills(currentCharacter).length > 6"
                        class="more-skills-mini"
                      >
                        +{{ getCharacterSkills(currentCharacter).length - 6 }}
                      </span>
                    </div>
                  </div>
                </div>

                <!-- 技能为空的提示卡片 -->
                <div class="detail-card empty" v-else>
                  <div class="detail-card-header">
                    <span class="detail-icon">🎯</span>
                    <h5 class="detail-title">拥有技能</h5>
                  </div>
                  <div class="detail-card-body">
                    <div class="empty-skills">
                      <span class="empty-text">暂无技能设置</span>
                      <button class="assign-btn" @click="editTheater">分配技能</button>
                    </div>
                  </div>
                </div>

                <!-- 剧情参与卡片 -->
                <div class="detail-card">
                  <div class="detail-card-header">
                    <span class="detail-icon">📊</span>
                    <h5 class="detail-title">剧情参与</h5>
                  </div>
                  <div class="detail-card-body">
                    <div class="stats-mini">
                      <div class="stat-mini-item">
                        <span class="stat-mini-number">{{
                          getCharacterSceneCount(currentCharacter.id)
                        }}</span>
                        <span class="stat-mini-text">参与场景</span>
                      </div>
                      <div class="stat-mini-item">
                        <span class="stat-mini-number">{{
                          getCharacterSettingsCount(currentCharacter.id)
                        }}</span>
                        <span class="stat-mini-text">角色设置</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 角色操作 -->
              <div class="character-actions-compact">
                <button
                  class="action-btn-compact primary"
                  @click="selectCharacter(currentCharacter.id)"
                >
                  <span class="btn-icon">✓</span>
                  查看详情
                </button>
                <button
                  class="action-btn-compact secondary"
                  @click="viewCharacterInScenes(currentCharacter.id)"
                >
                  <span class="btn-icon">🎬</span>
                  在场景中
                </button>
              </div>
            </div>
          </div>

          <!-- 剧场设置标签页 -->
          <div v-show="activeTab === 'settings'" class="tab-panel settings-panel">
            <div class="panel-header">
              <h3 class="panel-title">剧场设置与信息</h3>
            </div>

            <div class="settings-grid">
              <div class="settings-card">
                <h4>
                  <span class="info-icon">ℹ️</span>
                  基本信息
                </h4>
                <div class="setting-item">
                  <label>剧场名称</label>
                  <span>{{ theaterData.title || '未命名剧场' }}</span>
                </div>
                <div class="setting-item">
                  <label>创建日期</label>
                  <span>{{ theaterData.createdAt || '未知时间' }}</span>
                </div>
                <div class="setting-item">
                  <label>作者</label>
                  <span>{{ theaterData.author || 'AI智能生成器' }}</span>
                </div>
                <div class="setting-item">
                  <label>时代背景</label>
                  <span>{{ theaterData.era || '未设定' }}</span>
                </div>
                <div class="setting-item">
                  <label>故事地点</label>
                  <span>{{ theaterData.location || '未设定' }}</span>
                </div>
                <div class="setting-item">
                  <label>剧情摘要</label>
                  <span class="plot-summary-text">{{ theaterData.plotSummary || '暂无摘要' }}</span>
                </div>
              </div>

              <div class="settings-card">
                <h4>
                  <span class="feature-icon">✨</span>
                  剧场特性
                </h4>
                <div class="features-list">
                  <div v-for="feature in theaterData.features" :key="feature" class="feature-item">
                    <span class="check-icon">✅</span>
                    {{ feature }}
                  </div>
                  <div
                    v-if="!theaterData.features || theaterData.features.length === 0"
                    class="feature-item"
                  >
                    <span class="check-icon">ℹ️</span>
                    暂无特性标签
                  </div>
                </div>
              </div>

              <div class="settings-card">
                <h4>
                  <span class="stats-icon">📈</span>
                  统计信息
                </h4>
                <div class="stats-list">
                  <div class="stat-row">
                    <span>剧情节点</span>
                    <strong>{{ plotNodes.length }}</strong>
                  </div>
                  <div class="stat-row">
                    <span>角色数量</span>
                    <strong>{{ characters.length }}</strong>
                  </div>
                  <div class="stat-row">
                    <span>技能池</span>
                    <strong>{{ getTotalSkillsCount() }}</strong>
                  </div>
                  <div class="stat-row">
                    <span>分支路径</span>
                    <strong>{{ getTotalBranches() }}</strong>
                  </div>
                  <div class="stat-row">
                    <span>预计时长</span>
                    <strong>{{ getTotalDuration() }}分钟</strong>
                  </div>
                </div>
              </div>

              <div class="settings-card">
                <h4>
                  <span class="tools-icon">🛠️</span>
                  快捷操作
                </h4>
                <div class="quick-actions">
                  <button class="quick-action-btn" @click="exportTheater">
                    <span class="download-icon">💾</span>
                    导出剧场
                  </button>
                  <button class="quick-action-btn" @click="cloneTheater">
                    <span class="copy-icon">📋</span>
                    克隆剧场
                  </button>
                  <button class="quick-action-btn" @click="shareTheater">
                    <span class="share-icon">📤</span>
                    分享剧场
                  </button>
                  <button class="quick-action-btn" @click="editTheater">
                    <span class="edit-icon">✏️</span>
                    继续编辑
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作区域 -->
      <div class="action-area">
        <button class="btn btn-primary btn-large" @click="startExperience">
          <span class="play-icon">▶️</span>
          开始体验剧场
        </button>
        <div class="secondary-actions">
          <button class="btn btn-secondary" @click="editTheater">
            <span class="edit-icon">✏️</span>
            编辑剧场
          </button>
          <button class="btn btn-secondary" @click="shareTheater">
            <span class="share-icon">📤</span>
            分享剧场
          </button>
          <button class="btn btn-secondary" @click="copyLink">
            <span class="link-icon">🔗</span>
            复制链接
          </button>
          <button class="btn btn-secondary" @click="saveToFavorites">
            <span class="heart-icon">❤️</span>
            收藏
          </button>
        </div>
      </div>
    </div>

    <!-- 现代渐变脉冲加载动画 -->
    <div v-if="isLoading" class="loading-overlay">
      <div class="modern-loading">
        <div class="loading-circle-container">
          <div class="loading-circle"></div>
          <div class="loading-circle"></div>
          <div class="loading-circle"></div>
        </div>
        <div class="loading-text">
          <h3>{{ loadingTitle }}</h3>
          <p>{{ loadingMessage }}</p>
        </div>
        <div class="loading-progress">
          <div class="progress-bar" :style="{ width: `${loadingProgress}%` }"></div>
        </div>
      </div>
    </div>

    <!-- 节点和角色选择模态框 -->
    <div v-if="showSelectionModal" class="modal-overlay" @click.self="closeSelectionModal">
      <div class="selection-modal">
        <div class="modal-header">
          <h3>开始剧场体验</h3>
          <button class="close-btn" @click="closeSelectionModal">×</button>
        </div>

        <div class="modal-content">
          <div class="selection-step">
            <h4>选择起始节点</h4>
            <p>选择您想要开始体验的剧情节点：</p>
            <div class="nodes-selection">
              <div
                v-for="(node, index) in plotNodes"
                :key="node.id"
                class="node-option"
                :class="{ active: selectedNodeIndex === index }"
                @click="selectStartNode(index)"
              >
                <div class="node-option-marker">
                  <span>{{ index + 1 }}</span>
                </div>
                <div class="node-option-content">
                  <h5>{{ node.title }}</h5>
                  <p>{{ getNodeDescription(node) }}</p>
                  <div class="node-option-meta">
                    <span class="duration">{{ getNodeDuration(node) }}分钟</span>
                    <span class="difficulty" :class="getNodeDifficulty(node).class">
                      {{ getNodeDifficulty(node).label }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="selection-step">
            <h4>选择扮演角色</h4>
            <p>选择您想要扮演的角色：</p>
            <div class="characters-selection">
              <div
                v-for="(character, index) in characters"
                :key="character.id"
                class="character-option"
                :class="{ active: selectedCharacterIndex === index }"
                @click="selectPlayCharacter(index)"
              >
                <img
                  :src="character.avatar"
                  :alt="character.name"
                  class="character-option-avatar"
                />
                <div class="character-option-info">
                  <h5>{{ character.name }}</h5>
                  <p>{{ character.description.substring(0, 80) }}...</p>
                  <!-- 🔧 修复后的技能预览部分 -->
                  <div
                    class="character-option-skills"
                    v-if="getCharacterSkills(character).length > 0"
                  >
                    <span class="skills-label">技能:</span>
                    <div class="skills-preview">
                      <span
                        v-for="skill in getCharacterSkills(character).slice(0, 3)"
                        :key="skill"
                        class="skill-preview"
                        :title="`技能: ${skill}`"
                      >
                        {{ skill }}
                      </span>
                      <span v-if="getCharacterSkills(character).length > 3" class="more-skills">
                        +{{ getCharacterSkills(character).length - 3 }}
                      </span>
                    </div>
                  </div>
                  <!-- 技能为空时的提示 -->
                  <div class="character-option-skills" v-else>
                    <span class="skills-label">技能:</span>
                    <span class="no-skills-hint">待分配技能</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeSelectionModal">取消</button>
          <button
            class="btn btn-primary"
            @click="confirmStartExperience"
            :disabled="selectedNodeIndex === -1 || selectedCharacterIndex === -1"
          >
            开始体验
          </button>
        </div>
      </div>
    </div>

    <!-- 数据为空的提示 -->
    <div v-if="!hasData" class="empty-state">
      <div class="empty-content">
        <div class="empty-icon">🎭</div>
        <h3>暂无剧场数据</h3>
        <p>请先在创建页面生成剧场内容</p>
        <button class="btn btn-primary" @click="goToCreate">
          <span>✨</span>
          去创建剧场
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 🔧 API配置
const THEATER_DETAIL_API = 'http://localhost:8803'
const apiClient = axios.create({
  baseURL: THEATER_DETAIL_API,
  timeout: 30000,
})

// 类型定义
interface PlotNode {
  id: string
  title: string
  content: string
  characterSettings: any
  level: number
  node_type?: string
  parent_node_id?: number
  order_index?: number
  conditions?: any
  actions?: any
}

interface Character {
  id: string
  name: string
  description: string
  avatar: string
  selectedSkills: any
  personality?: string
  background?: string
  special_abilities?: any
}

interface TheaterData {
  title: string
  description: string
  era: string
  location: string
  createdAt: string
  author: string
  plotSummary: string
  features: string[]
}

// 🔧 API相关状态
const isLoadingFromAPI = ref(false)
const apiError = ref('')
const taskId = ref('')

// 响应式数据
const currentNodeIndex = ref(0)
const currentCharacterIndex = ref(0)
const isBookmarked = ref(false)
const activeTab = ref<'plot' | 'character' | 'settings'>('plot')

// 新增状态
const isLoading = ref(false)
const isSharing = ref(false)
const summaryExpanded = ref(false)
const charDescExpanded = ref(false)
const characterFilter = ref('all')
const timelineScrollLeft = ref(0)
const maxScrollLeft = ref(0)
const timelineTrack = ref<HTMLElement>()

// 选择相关状态
const showSelectionModal = ref(false)
const selectedNodeIndex = ref(-1)
const selectedCharacterIndex = ref(-1)

// 加载动画相关状态
const loadingTitle = ref('准备开始')
const loadingMessage = ref('正在加载剧场体验...')
const loadingProgress = ref(0)

// 数据状态
const theaterData = reactive<TheaterData>({
  title: '',
  description: '',
  era: '',
  location: '',
  createdAt: '',
  author: '',
  plotSummary: '',
  features: [],
})

const plotNodes = reactive<PlotNode[]>([])
const characters = reactive<Character[]>([])
const availableSkills = ref<string[]>([])

// 🔧 核心修改：从API获取剧场数据
const loadTheaterDataFromAPI = async (taskId: string) => {
  console.log('🎭 开始从API获取剧场详情，task_id:', taskId)

  isLoadingFromAPI.value = true
  apiError.value = ''

  // 设置加载动画
  isLoading.value = true
  loadingTitle.value = '加载剧场详情'
  loadingMessage.value = '正在从服务器获取剧场数据...'
  loadingProgress.value = 0

  const progressInterval = setInterval(() => {
    if (loadingProgress.value < 90) {
      loadingProgress.value += Math.random() * 20 + 5
    }
  }, 200)

  try {
    console.log('📡 调用API:', `${THEATER_DETAIL_API}/theater/${taskId}`)

    const response = await apiClient.get(`/theater/${taskId}`)

    console.log('📋 API响应:', response.data)

    if (response.data.success && response.data.data) {
      const theaterDetail = response.data.data.data

      // 更新剧场基本信息
      if (theaterDetail.theater_info) {
        Object.assign(theaterData, {
          title: theaterDetail.theater_info.title || '',
          description: theaterDetail.theater_info.description || '',
          era: theaterDetail.theater_info.era || '',
          location: theaterDetail.theater_info.location || '',
          createdAt: theaterDetail.theater_info.createdAt || '',
          author: theaterDetail.theater_info.author || '',
          plotSummary: theaterDetail.theater_info.plotSummary || '',
          features: theaterDetail.theater_info.features || [],
        })
        console.log('✅ 剧场信息加载完成')
      }

      // 更新剧情节点
      if (theaterDetail.script_nodes && Array.isArray(theaterDetail.script_nodes)) {
        plotNodes.splice(0)

        const processedNodes = theaterDetail.script_nodes.map((node: any, index: number) => ({
          id: node.id?.toString() || `node-${index}`,
          title: node.title || `节点 ${index + 1}`,
          content: node.content || '',
          characterSettings: node.characterSettings || {},
          level: node.level || 0,
          node_type: node.node_type,
          parent_node_id: node.parent_node_id,
          order_index: node.order_index || index,
          conditions: node.conditions,
          actions: node.actions,
        }))

        plotNodes.push(...processedNodes)
        console.log(`✅ 加载 ${plotNodes.length} 个剧情节点`)
      }

      // 更新角色信息
      if (theaterDetail.characters && Array.isArray(theaterDetail.characters)) {
        characters.splice(0)

        const processedCharacters = theaterDetail.characters.map((char: any, index: number) => ({
          id: char.id?.toString() || `char-${index}`,
          name: char.name || '未知角色',
          description: char.description || '暂无描述',
          avatar: char.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(char.name || 'Unknown')}&background=3b82f6&color=fff`,
          selectedSkills: char.selectedSkills || [],
          personality: char.personality,
          background: char.background,
          special_abilities: char.special_abilities,
        }))

        characters.push(...processedCharacters)
        console.log(`✅ 加载 ${characters.length} 个角色`)
      }

      // 更新技能池
      if (theaterDetail.available_skills && Array.isArray(theaterDetail.available_skills)) {
        availableSkills.value = theaterDetail.available_skills
        console.log(`✅ 加载 ${theaterDetail.available_skills.length} 个技能`)
      }

      loadingProgress.value = 100

      setTimeout(() => {
        clearInterval(progressInterval)
        isLoading.value = false
        isLoadingFromAPI.value = false

        console.log('🎉 剧场数据加载完成')
      }, 500)

    } else {
      throw new Error(response.data.message || '获取剧场数据失败')
    }

  } catch (error: any) {
    clearInterval(progressInterval)
    isLoading.value = false
    isLoadingFromAPI.value = false

    console.error('❌ 加载剧场数据失败:', error)

    if (error.response?.status === 404) {
      apiError.value = '剧场不存在或已被删除'
    } else if (error.code === 'ECONNREFUSED') {
      apiError.value = '无法连接到剧场详情服务，请确保服务正在运行'
    } else {
      apiError.value = error.response?.data?.message || error.message || '加载剧场数据失败'
    }

    // 显示错误提示并跳转
    setTimeout(() => {
      alert(`加载剧场失败: ${apiError.value}\n\n将跳转到创建页面`)
      goToCreate()
    }, 1000)
  }
}

// 🔧 修改数据加载逻辑 - 完全去除localStorage
const loadTheaterData = async () => {
  try {
    console.log('🔄 开始加载剧场数据...')

    // 1. 优先从路由参数获取task_id
    const routeTaskId = route.params.task_id as string

    if (routeTaskId) {
      console.log('📌 从路由参数获取到task_id:', routeTaskId)
      taskId.value = routeTaskId
      await loadTheaterDataFromAPI(routeTaskId)
      return
    }

    // 2. 从查询参数获取task_id
    const queryTaskId = route.query.task_id as string

    if (queryTaskId) {
      console.log('📌 从查询参数获取到task_id:', queryTaskId)
      taskId.value = queryTaskId
      await loadTheaterDataFromAPI(queryTaskId)
      return
    }

    // 3. 如果没有task_id，直接跳转到创建页面
    console.warn('⚠️ 未找到task_id参数')
    setTimeout(() => {
      alert('未找到剧场数据，将跳转到创建页面')
      goToCreate()
    }, 1000)

  } catch (error) {
    console.error('❌ 加载剧场数据失败:', error)
    setTimeout(() => {
      alert('加载剧场数据失败，将跳转到创建页面')
      goToCreate()
    }, 1000)
  }
}

// 🔧 技能数据标准化函数
const normalizeSkillsData = (rawSkills: any[]): string[] => {
  console.log('🔧 开始标准化技能数据，原始数据：', rawSkills)

  const normalizedSkills: string[] = []

  if (!Array.isArray(rawSkills)) {
    console.warn('⚠️ 技能数据不是数组格式，尝试转换')
    if (typeof rawSkills === 'string') {
      try {
        const parsed = JSON.parse(rawSkills)
        return normalizeSkillsData(Array.isArray(parsed) ? parsed : [parsed])
      } catch (e) {
        console.error('❌ 无法解析技能字符串:', e)
        return [rawSkills]
      }
    } else if (rawSkills && typeof rawSkills === 'object') {
      return normalizeSkillsData([rawSkills])
    } else {
      return []
    }
  }

  for (let i = 0; i < rawSkills.length; i++) {
    const skill = rawSkills[i]

    try {
      if (typeof skill === 'string') {
        const trimmedSkill = skill.trim()
        if (trimmedSkill && trimmedSkill.length > 1) {
          normalizedSkills.push(trimmedSkill)
        }
      } else if (skill && typeof skill === 'object') {
        if (skill.skills && Array.isArray(skill.skills)) {
          skill.skills.forEach((subSkill: any) => {
            if (typeof subSkill === 'string') {
              const trimmedSkill = subSkill.trim()
              if (trimmedSkill && trimmedSkill.length > 1) {
                normalizedSkills.push(trimmedSkill)
              }
            }
          })
        } else if (skill.name) {
          const skillName = skill.name.trim()
          if (skillName && skillName.length > 1) {
            normalizedSkills.push(skillName)
          }
        } else if (skill.skill) {
          const skillName = skill.skill.trim()
          if (skillName && skillName.length > 1) {
            normalizedSkills.push(skillName)
          }
        }
      } else if (Array.isArray(skill)) {
        const nestedSkills = normalizeSkillsData(skill)
        normalizedSkills.push(...nestedSkills)
      } else {
        const skillStr = String(skill).trim()
        if (skillStr && skillStr !== 'null' && skillStr !== 'undefined' && skillStr.length > 1) {
          normalizedSkills.push(skillStr)
        }
      }
    } catch (error) {
      console.error(`❌ 处理技能 ${i + 1} 时出错:`, error, '原始数据:', skill)
      continue
    }
  }

  const uniqueSkills = [...new Set(normalizedSkills)]
    .filter((skill) => skill && skill.length > 1 && skill.length < 100)
    .slice(0, 50)

  console.log(
    `🎯 技能标准化完成: 原始 ${rawSkills.length} → 处理后 ${normalizedSkills.length} → 去重后 ${uniqueSkills.length}`,
  )

  return uniqueSkills
}

// 🔧 修复的技能相关方法
const getCharacterSkills = (character: Character): string[] => {
  if (!character || !character.selectedSkills) {
    console.log(`⚠️ 角色 ${character?.name || '未知'} 没有技能数据`)
    return []
  }

  const skills = character.selectedSkills
  console.log(`🔍 处理角色 ${character.name} 的技能:`, skills, typeof skills)

  if (Array.isArray(skills)) {
    const validSkills = skills.filter(
      (skill) => typeof skill === 'string' && skill.trim().length > 0,
    )
    console.log(`✅ 角色 ${character.name} - 数组格式技能:`, validSkills)
    return validSkills
  }

  if (typeof skills === 'string') {
    try {
      const parsed = JSON.parse(skills)
      console.log(`🔍 角色 ${character.name} - 解析JSON字符串:`, parsed)
      return normalizeSkillsData(Array.isArray(parsed) ? parsed : [parsed])
    } catch (e) {
      console.warn(`⚠️ 角色 ${character.name} - JSON解析失败，当作单个技能:`, e)
      return skills.trim() ? [skills.trim()] : []
    }
  }

  if (typeof skills === 'object') {
    console.log(`🔍 角色 ${character.name} - 对象格式技能:`, skills)
    const normalized = normalizeSkillsData([skills])
    console.log(`✅ 角色 ${character.name} - 对象格式处理结果:`, normalized)
    return normalized
  }

  console.warn(`⚠️ 角色 ${character.name} - 未知技能格式:`, skills)
  return []
}

const getCharacterSkillCategory = (character: Character): string => {
  if (!character || !character.selectedSkills) return ''

  const skills = character.selectedSkills

  if (typeof skills === 'string') {
    try {
      const parsed = JSON.parse(skills)
      if (parsed && typeof parsed === 'object' && parsed.category) {
        return parsed.category
      }
    } catch {
      return ''
    }
  }

  if (typeof skills === 'object' && skills.category && typeof skills.category === 'string') {
    return skills.category
  }

  return ''
}

// 计算属性
const currentCharacter = computed(() => filteredCharacters.value[currentCharacterIndex.value])
const currentNodeInfo = computed(() => plotNodes[currentNodeIndex.value] || {})

const filteredCharacters = computed(() => {
  switch (characterFilter.value) {
    case 'main':
      return characters.filter((c, index) => index < 2)
    case 'support':
      return characters.filter((c, index) => index >= 2)
    default:
      return characters
  }
})

const hasData = computed(() => {
  return theaterData.title && plotNodes.length > 0 && characters.length > 0
})

// 计算方法
const getTotalBranches = () => {
  return plotNodes.reduce((total, node) => {
    const settings = node.characterSettings || {}
    return total + Object.keys(settings).length
  }, 0)
}

const getTotalDuration = () => {
  return plotNodes.reduce((total, node) => {
    return total + getNodeDuration(node)
  }, 0)
}

const getTotalSkillsCount = () => {
  const allSkills = new Set<string>()

  characters.forEach((character) => {
    const skills = getCharacterSkills(character)
    skills.forEach((skill) => allSkills.add(skill))
  })

  if (availableSkills.value && Array.isArray(availableSkills.value)) {
    availableSkills.value.forEach((skill) => allSkills.add(skill))
  }

  return allSkills.size
}

const getNodeDuration = (node: PlotNode) => {
  if (!node) return 0
  const contentLength = (node.content || '').replace(/<[^>]*>/g, '').length
  const baseTime = 3
  const timePerChar = contentLength / 100
  return Math.max(baseTime, Math.round(baseTime + timePerChar))
}

const getNodeDifficulty = (node: PlotNode) => {
  if (!node) return { label: '简单', class: 'difficulty-easy', icon: '🍃' }
  const settingsCount = Object.keys(node.characterSettings || {}).length
  if (settingsCount >= 3) return { label: '复杂', class: 'difficulty-hard', icon: '🔥' }
  if (settingsCount >= 2) return { label: '中等', class: 'difficulty-medium', icon: '⚖️' }
  return { label: '简单', class: 'difficulty-easy', icon: '🍃' }
}

const getNodeType = (node: PlotNode) => {
  if (!node || !node.content) return 'general'
  const content = node.content.toLowerCase()
  if (content.includes('战斗') || content.includes('冲突')) return 'combat'
  if (content.includes('谜题') || content.includes('解决')) return 'puzzle'
  if (content.includes('对话') || content.includes('交流')) return 'story'
  return 'general'
}

const getNodeTypeIcon = (node: PlotNode) => {
  const type = getNodeType(node)
  const icons = {
    combat: '⚔️',
    puzzle: '🧩',
    story: '📖',
    general: '⭕',
  }
  return icons[type] || '⭕'
}

const getNodeDescription = (node: PlotNode) => {
  if (!node || !node.content) return '暂无内容'
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = node.content
  const text = tempDiv.textContent || tempDiv.innerText || ''
  return text.substring(0, 100) + (text.length > 100 ? '...' : '')
}

const getNodeFeatures = (node: PlotNode) => {
  if (!node) return []
  const features = []
  const settings = node.characterSettings || {}

  if (Object.keys(settings).length > 0) {
    features.push('角色互动')
  }

  const type = getNodeType(node)
  switch (type) {
    case 'combat':
      features.push('战斗场景')
      break
    case 'puzzle':
      features.push('解谜挑战')
      break
    case 'story':
      features.push('剧情对话')
      break
  }

  const difficulty = getNodeDifficulty(node)
  features.push(difficulty.label)

  return features
}

const getNodeParticipants = (nodeId: string) => {
  const node = plotNodes.find((n) => n.id === nodeId)
  if (!node || !node.characterSettings) return []
  return Object.keys(node.characterSettings)
}

const getCharacterName = (characterId: string) => {
  return characters.find((c) => c.id === characterId)?.name || '未知角色'
}

const getCharacterAvatar = (characterId: string) => {
  return characters.find((c) => c.id === characterId)?.avatar || ''
}

const getCurrentNodeCharacterSettings = () => {
  const node = currentNodeInfo.value
  if (!node || !node.characterSettings) return []

  return Object.entries(node.characterSettings).map(([charId, settings]: [string, any]) => {
    const character = characters.find((c) => c.id === charId)
    return {
      characterId: charId,
      name: character?.name || '未知角色',
      avatar: character?.avatar || '',
      description: character?.description || '',
      behaviors: settings.behaviors || [],
      conditions: settings.conditions || [],
      branches: settings.branches || [],
    }
  })
}

const getCharacterSceneCount = (characterId: string) => {
  return plotNodes.filter((node) => node.characterSettings && node.characterSettings[characterId])
    .length
}

const getCharacterSettingsCount = (characterId: string) => {
  return plotNodes.reduce((total, node) => {
    if (node.characterSettings && node.characterSettings[characterId]) {
      const settings = node.characterSettings[characterId]
      return total + (settings.behaviors?.length || 0) + (settings.conditions?.length || 0)
    }
    return total
  }, 0)
}

// 导航和操作方法
const goBack = () => {
  router.push('/TheaterList')
}

const goToCreate = () => {
  console.log('🔄 跳转到创建页面')
  router.push('/theaterCreate')
}

// 🔧 修改：去除localStorage的编辑方法
const editTheater = () => {
  if (!hasData.value) {
    alert('没有可编辑的剧场数据')
    return
  }

  // 直接跳转，编辑页面会根据task_id从接口获取数据
  router.push({
    path: '/theaterCreate',
    query: { task_id: route.params.task_id }
  })
}

// 🔧 修改：去除localStorage的开始体验方法
const startExperience = () => {
  if (!hasData.value) {
    alert('请先生成剧场内容')
    return
  }

  showSelectionModal.value = true

  if (selectedNodeIndex.value === -1) {
    selectedNodeIndex.value = 0
  }
  if (selectedCharacterIndex.value === -1) {
    selectedCharacterIndex.value = 0
  }
}

const closeSelectionModal = () => {
  showSelectionModal.value = false
}

const selectStartNode = (index: number) => {
  selectedNodeIndex.value = index
}

const selectPlayCharacter = (index: number) => {
  selectedCharacterIndex.value = index
}

// 🔧 修改：去除localStorage的确认开始体验方法
const confirmStartExperience = () => {
  if (selectedNodeIndex.value === -1 || selectedCharacterIndex.value === -1) {
    alert('请先选择起始节点和扮演角色')
    return
  }

  isLoading.value = true
  loadingTitle.value = '启动剧场'
  loadingMessage.value = '正在初始化剧场环境...'
  loadingProgress.value = 0

  const interval = setInterval(() => {
    loadingProgress.value += Math.random() * 25 + 10

    if (loadingProgress.value >= 30 && loadingProgress.value < 60) {
      loadingMessage.value = '加载角色和剧情...'
    } else if (loadingProgress.value >= 60 && loadingProgress.value < 90) {
      loadingMessage.value = '准备舞台效果...'
    } else if (loadingProgress.value >= 90) {
      loadingMessage.value = '即将开始体验...'
    }

    if (loadingProgress.value >= 100) {
      clearInterval(interval)
      setTimeout(() => {
        isLoading.value = false
        closeSelectionModal()

        // 🎯 直接跳转到体验页面，只传递必要的参数
        // Theater.vue 会根据这些参数从接口获取所有数据
        router.push({
          path: '/theater',
          query: {
            task_id: route.params.task_id,
            character_id: characters[selectedCharacterIndex.value].id,
            node_id: plotNodes[selectedNodeIndex.value].id
          }
        })
      }, 800)
    }
  }, 300)
}

const shareTheater = async () => {
  if (!hasData.value) {
    alert('请先生成剧场内容')
    return
  }

  isSharing.value = true
  try {
    const shareData = {
      title: theaterData.title,
      text: theaterData.description,
      url: window.location.href,
    }

    if (navigator.share) {
      await navigator.share(shareData)
    } else {
      await navigator.clipboard.writeText(window.location.href)
      alert('链接已复制到剪贴板')
    }
  } catch (error) {
    console.error('分享失败:', error)
  } finally {
    isSharing.value = false
  }
}

const toggleBookmark = () => {
  isBookmarked.value = !isBookmarked.value
}

const selectNode = (index: number) => {
  currentNodeIndex.value = index
}

const copyLink = async () => {
  try {
    await navigator.clipboard.writeText(window.location.href)
    alert('链接已复制！')
  } catch (error) {
    console.error('复制失败:', error)
  }
}

const scrollTimeline = (direction: 'left' | 'right') => {
  if (!timelineTrack.value) return
  const scrollAmount = 300
  const currentScroll = timelineTrack.value.scrollLeft
  const newScroll =
    direction === 'left'
      ? Math.max(0, currentScroll - scrollAmount)
      : Math.min(maxScrollLeft.value, currentScroll + scrollAmount)

  timelineTrack.value.scrollTo({ left: newScroll, behavior: 'smooth' })
}

const updateScrollPosition = () => {
  if (!timelineTrack.value) return
  timelineScrollLeft.value = timelineTrack.value.scrollLeft
  maxScrollLeft.value = timelineTrack.value.scrollWidth - timelineTrack.value.clientWidth
}

const switchTab = (tab: 'plot' | 'character' | 'settings') => {
  activeTab.value = tab
}

const toggleSummaryExpanded = () => {
  summaryExpanded.value = !summaryExpanded.value
}

const prevCharacter = () => {
  if (currentCharacterIndex.value > 0) {
    currentCharacterIndex.value--
  }
}

const nextCharacter = () => {
  if (currentCharacterIndex.value < filteredCharacters.value.length - 1) {
    currentCharacterIndex.value++
  }
}

const goToCharacter = (index: number) => {
  currentCharacterIndex.value = index
}

const selectCharacter = (characterId: string) => {
  console.log('选择角色:', characterId)
}

const viewCharacterInScenes = (characterId: string) => {
  activeTab.value = 'plot'
  console.log('查看角色在场景中的表现:', characterId)
}

const filterCharacters = () => {
  currentCharacterIndex.value = 0
}

const filterByFeature = (feature: string) => {
  console.log('按特征过滤:', feature)
}

const previewNode = () => {
  console.log('预览节点:', currentNodeInfo.value.title)
}

const exportNode = () => {
  console.log('导出节点:', currentNodeInfo.value.title)
}

const exportTheater = () => {
  if (!hasData.value) {
    alert('请先生成剧场内容')
    return
  }

  const exportData = {
    theater_info: theaterData,
    script_nodes: plotNodes,
    characters: characters,
    available_skills: availableSkills.value,
    exported_at: new Date().toISOString(),
  }

  const dataStr = JSON.stringify(exportData, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)

  const link = document.createElement('a')
  link.href = url
  link.download = `${theaterData.title || '剧场'}.json`
  link.click()

  URL.revokeObjectURL(url)
}

// 🔧 修改：去除localStorage的克隆方法
const cloneTheater = () => {
  if (!hasData.value) {
    alert('请先生成剧场内容')
    return
  }

  // 直接跳转，创建页面会根据需要处理克隆逻辑
  router.push({
    path: '/theaterCreate',
    query: {
      task_id: route.params.task_id,
      action: 'clone'
    }
  })
}

const saveToFavorites = () => {
  console.log('保存到收藏夹')
}

// 🔧 调试函数
const debugCharacterSkills = (character: Character) => {
  console.log(`🔍 角色技能调试 - ${character.name}:`, {
    originalSkills: character.selectedSkills,
    skillsType: typeof character.selectedSkills,
    isArray: Array.isArray(character.selectedSkills),
    normalizedSkills: getCharacterSkills(character),
    category: getCharacterSkillCategory(character),
    skillsCount: getCharacterSkills(character).length,
  })
}

// 🔧 生命周期钩子
onMounted(async () => {
  console.log('🎭 组件挂载')
  await loadTheaterData()

  if (import.meta.env.DEV) {
    nextTick(() => {
      characters.forEach((character, index) => {
        console.log(`🔍 调试角色 ${index + 1}:`)
        debugCharacterSkills(character)
      })
    })
  }

  nextTick(() => {
    if (timelineTrack.value) {
      updateScrollPosition()
    }
  })
})

// 🔧 监听路由变化
watch(() => route.params.task_id, async (newTaskId) => {
  if (newTaskId && newTaskId !== taskId.value) {
    console.log('📍 路由task_id变化，重新加载数据:', newTaskId)
    taskId.value = newTaskId as string
    await loadTheaterDataFromAPI(newTaskId as string)
  }
})

watch(timelineTrack, (newVal) => {
  if (newVal) {
    newVal.addEventListener('scroll', updateScrollPosition)
  }
})
</script>

<style scoped>
.theater-preview-app {
  --primary-blue: #3b82f6;
  --ai-gradient: linear-gradient(135deg, #8b5cf6, #ec4899);
  --ai-glow: 0 0 20px rgba(139, 92, 246, 0.3);

  margin: 0;
  padding: 2rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f7ff, #e6f3ff);
  color: #334155;
}

.container {
  max-width: 80vw;
  margin: 0 auto;
}

/* 顶部导航 */
.top-nav {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 1rem;
  padding: 1rem 2rem;
  margin-bottom: 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.1);
}

.nav-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.back-btn {
  background: none;
  border: none;
  color: var(--primary-blue);
  font-size: 1.2rem;
  cursor: pointer;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.back-btn:hover {
  background: rgba(59, 130, 246, 0.1);
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  background: var(--ai-gradient);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.nav-right {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 0.75rem;
  border: none;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  position: relative;
  overflow: hidden;
}

.btn-primary {
  background: var(--primary-blue);
  color: white;
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.9);
  color: #334155;
  border: 1px solid #e2e8f0;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(59, 130, 246, 0.15);
}

.btn-large {
  padding: 1rem 2rem;
  font-size: 1.125rem;
}

/* 🔧 优化后的横幅样式 */
.banner {
  background: linear-gradient(135deg, #3b82f6 0%, #06b6d4 50%, #8b5cf6 100%);
  border-radius: 1.5rem;
  margin-bottom: 2rem;
  position: relative;
  overflow: hidden;
  min-height: 200px;
  box-shadow: 0 8px 32px rgba(59, 130, 246, 0.15);
}

.banner-content {
  position: relative;
  z-index: 2;
  padding: 2rem;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  height: 100%;
  backdrop-filter: blur(10px);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
}

.banner-main {
  display: flex;
  align-items: flex-start;
  gap: 2rem;
  flex: 1;
}

.banner-info {
  color: white;
  flex: 1;
  max-width: 60%;
}

.theater-title {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 0.75rem;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  line-height: 1.2;
}

.theater-description {
  font-size: 1rem;
  margin-bottom: 1.5rem;
  opacity: 0.95;
  line-height: 1.5;
  text-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
}

.meta-badges {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.meta-badge {
  background: rgba(255, 255, 255, 0.2);
  padding: 0.5rem 1rem;
  border-radius: 1.5rem;
  backdrop-filter: blur(20px);
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.9rem;
  font-weight: 500;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.badge-icon {
  font-size: 0.8rem;
}

.banner-stats {
  display: flex;
  gap: 1.5rem;
  align-items: center;
  margin-top: 1rem;
}

.stat-mini {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: white;
  background: rgba(255, 255, 255, 0.1);
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-mini-value {
  font-size: 1.25rem;
  font-weight: 700;
  line-height: 1;
}

.stat-mini-label {
  font-size: 0.75rem;
  opacity: 0.9;
  margin-top: 0.25rem;
}

.banner-actions {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  align-items: flex-end;
}

.action-btn {
  background: rgba(255, 255, 255, 0.95);
  color: #3b82f6;
  border: none;
  padding: 0.75rem 1.25rem;
  border-radius: 0.75rem;
  backdrop-filter: blur(10px);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
  font-weight: 600;
  font-size: 0.9rem;
  min-width: 120px;
  justify-content: center;
}

.action-btn.primary {
  background: linear-gradient(135deg, #10b981, #06b6d4);
  color: white;
  box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.action-btn.primary:hover {
  box-shadow: 0 6px 25px rgba(16, 185, 129, 0.4);
}

.action-btn.loading {
  pointer-events: none;
  opacity: 0.7;
}

.icon-action-btn {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.95);
  color: #3b82f6;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  font-size: 1.2rem;
}

.icon-action-btn:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.icon-action-btn.bookmarked {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
}

.banner-decoration {
  position: absolute;
  inset: 0;
  pointer-events: none;
  z-index: 1;
}

.decoration-orb {
  position: absolute;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1), transparent 70%);
  animation: float-glow 8s ease-in-out infinite;
}

.orb-1 {
  width: 100px;
  height: 100px;
  top: 10%;
  right: 10%;
  animation-delay: 0s;
}

.orb-2 {
  width: 60px;
  height: 60px;
  top: 60%;
  right: 25%;
  animation-delay: -2.5s;
}

.orb-3 {
  width: 80px;
  height: 80px;
  top: 30%;
  right: 45%;
  animation-delay: -5s;
}

@keyframes float-glow {
  0%,
  100% {
    transform: translateY(0px) scale(1);
    opacity: 0.6;
  }
  50% {
    transform: translateY(-20px) scale(1.1);
    opacity: 0.8;
  }
}

/* 故事导航保持原样 */
.story-navigation {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 1rem;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
}
.nav-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.5rem;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.progress-info {
  text-align: right;
}

.current-node {
  font-size: 1.1rem;
  font-weight: 600;
  color: #3b82f6;
  display: block;
  margin-bottom: 0.25rem;
}

.progress-text {
  font-size: 0.875rem;
  color: #64748b;
  background: rgba(59, 130, 246, 0.1);
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
}

/* 时间线导航 */
.timeline-navigation {
  display: flex;
  justify-content: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.timeline-nav-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.timeline-nav-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  color: white;
  transform: scale(1.1);
}

.timeline-nav-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 时间线轨道 */
.timeline-track {
  display: flex;
  gap: 1rem;
  overflow-x: auto;
  padding: 1rem 0;
  scroll-behavior: smooth;
}

.timeline-track::-webkit-scrollbar {
  height: 6px;
}

.timeline-track::-webkit-scrollbar-track {
  background: rgba(59, 130, 246, 0.1);
  border-radius: 3px;
}

.timeline-track::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  border-radius: 3px;
}

/* 时间线节点 */
.timeline-node {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 280px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.timeline-node:hover {
  transform: translateY(-4px);
}

.timeline-node.active {
  transform: translateY(-6px);
}

.node-marker {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 1rem;
  z-index: 2;
}

.node-dot {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.node-type {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.7rem;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

/* 节点状态样式 */
.timeline-node.completed .node-dot {
  background: linear-gradient(135deg, #10b981, #06b6d4);
  color: white;
}

.timeline-node.active .node-dot {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  color: white;
  transform: scale(1.1);
  box-shadow:
    0 0 0 4px rgba(59, 130, 246, 0.2),
    0 6px 20px rgba(59, 130, 246, 0.3);
}

.timeline-node.upcoming .node-dot {
  background: rgba(255, 255, 255, 0.9);
  color: #64748b;
  border: 2px solid rgba(59, 130, 246, 0.3);
}

.node-content {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.02) 0%, rgba(6, 182, 212, 0.02) 100%);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 1rem;
  padding: 1.5rem;
  transition: all 0.3s ease;
}

.timeline-node:hover .node-content,
.timeline-node.active .node-content {
  background: rgba(255, 255, 255, 0.95);
  border-color: #3b82f6;
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.15);
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.75rem;
}

.node-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #334155;
  margin: 0;
  flex: 1;
}

.node-participants {
  display: flex;
  gap: 0.25rem;
  margin-left: 1rem;
}

.participant-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.participant-avatar:hover {
  transform: scale(1.2);
  z-index: 10;
}

.participant-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.node-description {
  font-size: 0.9rem;
  color: #64748b;
  margin-bottom: 1rem;
  line-height: 1.5;
}

.node-features {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  margin-bottom: 1rem;
}

.feature-badge {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  padding: 0.2rem 0.6rem;
  border-radius: 0.75rem;
  font-size: 0.75rem;
  font-weight: 500;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.feature-more {
  background: rgba(147, 51, 234, 0.1);
  color: #8b5cf6;
  padding: 0.2rem 0.6rem;
  border-radius: 0.75rem;
  font-size: 0.75rem;
  font-weight: 500;
  border: 1px solid rgba(147, 51, 234, 0.2);
}

.node-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.75rem;
  color: #64748b;
}

.node-duration {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.node-difficulty {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.2rem 0.5rem;
  border-radius: 0.5rem;
}

.difficulty-easy {
  background: rgba(16, 185, 129, 0.1);
  color: #10b981;
}

.difficulty-medium {
  background: rgba(245, 158, 11, 0.1);
  color: #f59e0b;
}

.difficulty-hard {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

/* 节点连接线 */
.node-connector {
  position: absolute;
  top: 24px;
  right: -0.5rem;
  width: 1rem;
  height: 2px;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  opacity: 0.6;
  z-index: 1;
}

.timeline-node:last-child .node-connector {
  display: none;
}

/* 进度条 */
.timeline-progress {
  position: absolute;
  top: 48px;
  left: 24px;
  height: 3px;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 1.5px;
  width: calc(100% - 48px);
  z-index: 0;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  border-radius: 1.5px;
  transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 统一内容区域 */
.unified-content {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 1rem;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
  border: 1px solid rgba(59, 130, 246, 0.1);
  margin-bottom: 2rem;
  overflow: hidden;
  min-height: 500px;
  display: flex;
  flex-direction: column;
}

/* 标签页导航 */
.content-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.5);
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
  position: relative;
}

.tab-btn {
  flex: 1;
  padding: 1rem 2rem;
  background: none;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  font-weight: 600;
  color: #64748b;
  transition: all 0.3s ease;
  position: relative;
}

.tab-btn:hover {
  background: rgba(59, 130, 246, 0.05);
  color: #3b82f6;
}

.tab-btn.active {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  color: #3b82f6;
}

.tab-indicator {
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  border-radius: 1.5px;
}

/* 标签页内容 */
.tab-content {
  flex: 1;
  overflow: hidden;
}

.tab-panel {
  height: 100%;
  padding: 1.5rem;
  overflow-y: auto;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.tab-panel::-webkit-scrollbar {
  width: 8px;
}

.tab-panel::-webkit-scrollbar-track {
  background: rgba(59, 130, 246, 0.1);
  border-radius: 4px;
}

.tab-panel::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  border-radius: 4px;
}

/* 🔧 紧凑的面板头部 */
.panel-header-compact {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.panel-title-compact {
  font-size: 1.25rem;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  margin: 0;
}

.node-status-compact {
  display: flex;
  align-items: center;
}

.status-badge-compact {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.75rem;
  font-weight: 600;
}

.status-badge-compact.in-progress {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(6, 182, 212, 0.1) 100%);
  color: #3b82f6;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.status-badge-compact.completed {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(5, 150, 105, 0.1) 100%);
  color: #10b981;
  border: 1px solid rgba(16, 185, 129, 0.2);
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn-mini {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: rgba(59, 130, 246, 0.1);
  border: 1px solid rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  font-size: 0.8rem;
}

.action-btn-mini:hover {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  color: white;
  transform: scale(1.1);
}

/* 🔧 紧凑的内容网格 */
.content-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

.content-card {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.03) 0%, rgba(6, 182, 212, 0.03) 100%);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 0.75rem;
  padding: 1rem;
  transition: all 0.3s ease;
}

.content-card.wide {
  grid-column: 1;
}

.content-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.75rem;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
  font-weight: 600;
  color: #3b82f6;
  margin: 0;
}

.card-title .icon {
  font-size: 0.9rem;
}

.expand-toggle {
  background: none;
  border: none;
  color: #3b82f6;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 50%;
  transition: all 0.3s ease;
  font-size: 0.8rem;
}

.expand-toggle:hover {
  background: rgba(59, 130, 246, 0.1);
  transform: scale(1.1);
}

.card-body {
  transition: all 0.3s ease;
}

.content-preview {
  max-height: 100px;
  overflow-y: auto;
  padding: 0.75rem;
  background: #f8fafc;
  border-radius: 0.5rem;
  border: 1px solid rgba(59, 130, 246, 0.1);
  line-height: 1.5;
  font-size: 0.9rem;
}

.card-body.expanded .content-preview {
  max-height: 200px;
}

.content-details {
  margin-top: 0.75rem;
  padding-top: 0.75rem;
  border-top: 1px solid rgba(59, 130, 246, 0.1);
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.detail-row {
  display: flex;
  gap: 0.5rem;
  font-size: 0.85rem;
}

.detail-label {
  color: #64748b;
  font-weight: 500;
}

.detail-value {
  color: #3b82f6;
  font-weight: 600;
}

.feature-tags-compact {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.feature-tag-compact {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  color: #3b82f6;
  padding: 0.35rem 0.75rem;
  border-radius: 0.75rem;
  font-size: 0.8rem;
  font-weight: 600;
  border: 1px solid rgba(59, 130, 246, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.feature-tag-compact:hover {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  color: white;
  transform: translateY(-1px);
}

.count-badge {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  padding: 0.15rem 0.4rem;
  border-radius: 0.75rem;
  font-size: 0.7rem;
  font-weight: 500;
  margin-left: 0.5rem;
}

.character-settings-compact {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.character-setting-mini {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 0.5rem;
  border: 1px solid rgba(59, 130, 246, 0.1);
  transition: all 0.3s ease;
}

.character-setting-mini:hover {
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-1px);
}

.setting-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.setting-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.setting-info {
  flex: 1;
}

.setting-name {
  font-weight: 600;
  color: #3b82f6;
  font-size: 0.9rem;
}

.setting-behaviors {
  display: flex;
  gap: 0.35rem;
  margin-top: 0.35rem;
  flex-wrap: wrap;
}

.behavior-mini {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  padding: 0.15rem 0.4rem;
  border-radius: 0.35rem;
  font-size: 0.7rem;
  font-weight: 500;
}

.more-behaviors {
  background: rgba(147, 51, 234, 0.1);
  color: #8b5cf6;
  padding: 0.15rem 0.4rem;
  border-radius: 0.35rem;
  font-size: 0.7rem;
  font-weight: 500;
}

/* 🔧 紧凑的角色面板 */
.character-controls-compact {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.character-nav {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.nav-btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  border: 1px solid rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  font-size: 0.8rem;
}

.nav-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  color: white;
  transform: scale(1.1);
}

.nav-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.nav-info {
  font-size: 0.8rem;
  color: #64748b;
  font-weight: 500;
  background: rgba(59, 130, 246, 0.1);
  padding: 0.2rem 0.6rem;
  border-radius: 0.75rem;
}

.filter-select {
  background: rgba(59, 130, 246, 0.05);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 0.5rem;
  padding: 0.4rem 0.8rem;
  color: #3b82f6;
  font-weight: 500;
  cursor: pointer;
  font-size: 0.85rem;
}

.character-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.character-card-compact {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 1rem;
  padding: 1.25rem;
}

.character-main {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  margin-bottom: 1rem;
}

.character-avatar-section {
  position: relative;
  flex-shrink: 0;
}

.character-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.character-status {
  position: absolute;
  bottom: -2px;
  right: -2px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #3b82f6;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.6rem;
  border: 2px solid white;
}

.character-info {
  flex: 1;
}

.character-name {
  font-size: 1.25rem;
  font-weight: 700;
  margin-bottom: 0.25rem;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.character-role {
  font-size: 0.9rem;
  color: #64748b;
  font-weight: 500;
  margin-bottom: 0.5rem;
}

.character-desc {
  max-height: 40px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.character-desc.expanded {
  max-height: none;
}

.character-desc p {
  font-size: 0.85rem;
  color: #64748b;
  line-height: 1.4;
  margin-bottom: 0.5rem;
}

.desc-toggle {
  background: none;
  border: none;
  color: #3b82f6;
  cursor: pointer;
  font-size: 0.75rem;
  transition: all 0.3s ease;
}

.desc-toggle:hover {
  color: #2563eb;
}

.character-indicators-compact {
  display: flex;
  gap: 0.5rem;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.char-indicator-mini {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.char-indicator-mini:hover {
  transform: scale(1.1);
}

.char-indicator-mini.active {
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.char-indicator-mini img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.more-chars {
  font-size: 0.75rem;
  color: #64748b;
  font-weight: 500;
  background: rgba(107, 114, 128, 0.1);
  padding: 0.2rem 0.5rem;
  border-radius: 1rem;
}

.character-details-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

.detail-card {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.03) 0%, rgba(6, 182, 212, 0.03) 100%);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 0.75rem;
  padding: 1rem;
  transition: all 0.3s ease;
}

.detail-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.08);
}

.detail-card.empty {
  background: linear-gradient(135deg, rgba(139, 92, 246, 0.03) 0%, rgba(59, 130, 246, 0.03) 100%);
  border: 1px dashed rgba(139, 92, 246, 0.2);
}

.detail-card-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.detail-icon {
  font-size: 0.9rem;
}

.detail-title {
  font-size: 0.9rem;
  font-weight: 600;
  color: #3b82f6;
  margin: 0;
}

.skill-category-mini {
  font-size: 0.7rem;
  color: #8b5cf6;
  font-weight: 500;
  margin-left: auto;
}

.detail-card-body {
  /* 内容区域样式 */
}

.skills-compact {
  display: flex;
  gap: 0.35rem;
  flex-wrap: wrap;
}

.skill-mini {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  padding: 0.25rem 0.5rem;
  border-radius: 0.5rem;
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.skill-mini:hover {
  background: #3b82f6;
  color: white;
  transform: translateY(-1px);
}

.more-skills-mini {
  background: rgba(107, 114, 128, 0.1);
  color: #6b7280;
  padding: 0.25rem 0.5rem;
  border-radius: 0.5rem;
  font-size: 0.75rem;
  font-weight: 500;
}

.empty-skills {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  padding: 1rem;
}

.empty-text {
  color: #8b5cf6;
  font-size: 0.85rem;
  font-style: italic;
}

.assign-btn {
  background: rgba(139, 92, 246, 0.1);
  color: #8b5cf6;
  border: 1px solid rgba(139, 92, 246, 0.2);
  padding: 0.35rem 0.75rem;
  border-radius: 0.5rem;
  cursor: pointer;
  font-size: 0.75rem;
  transition: all 0.3s ease;
}

.assign-btn:hover {
  background: #8b5cf6;
  color: white;
}

.stats-mini {
  display: flex;
  justify-content: space-around;
  gap: 1rem;
}

.stat-mini-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-mini-number {
  font-size: 1.25rem;
  font-weight: 700;
  color: #3b82f6;
  line-height: 1;
}

.stat-mini-text {
  font-size: 0.75rem;
  color: #64748b;
  margin-top: 0.25rem;
}

.character-actions-compact {
  display: flex;
  gap: 0.75rem;
  justify-content: center;
  flex-wrap: wrap;
}

.action-btn-compact {
  padding: 0.6rem 1.25rem;
  border-radius: 0.6rem;
  border: none;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.35rem;
  font-size: 0.85rem;
}

.action-btn-compact.primary {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  color: white;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

.action-btn-compact.primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.action-btn-compact.secondary {
  background: rgba(255, 255, 255, 0.9);
  color: #3b82f6;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.action-btn-compact.secondary:hover {
  background: white;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

.btn-icon {
  font-size: 0.8rem;
}

/* 设置面板保持原样 */
.settings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
}

.settings-card {
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: 1rem;
  padding: 1.5rem;
  transition: all 0.3s ease;
}

.settings-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
}

.settings-card h4 {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.1rem;
  font-weight: 600;
  color: #3b82f6;
  margin-bottom: 1rem;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 0;
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-item label {
  font-weight: 500;
  color: #64748b;
}

.setting-item span {
  color: #334155;
  font-weight: 500;
}

.plot-summary-text {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 1.5;
}

.features-list,
.stats-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.9rem;
  color: #334155;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
}

.stat-row span {
  color: #64748b;
}

.stat-row strong {
  color: #3b82f6;
  font-weight: 600;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.quick-action-btn {
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(59, 130, 246, 0.1);
  color: #3b82f6;
  padding: 0.75rem 1rem;
  border-radius: 0.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 500;
}

.quick-action-btn:hover {
  background: white;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
}

/* 底部操作区域 */
.action-area {
  background: linear-gradient(
    135deg,
    rgba(59, 130, 246, 0.1) 0%,
    rgba(147, 51, 234, 0.1) 25%,
    rgba(236, 72, 153, 0.1) 50%,
    rgba(6, 182, 212, 0.1) 100%
  );
  border-radius: 1rem;
  padding: 2rem;
  text-align: center;
  border: 1px solid rgba(59, 130, 246, 0.1);
  position: relative;
  overflow: hidden;
}

.action-area::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(59, 130, 246, 0.03) 0%, transparent 70%);
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.secondary-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  flex-wrap: wrap;
  position: relative;
  z-index: 1;
}

/* 现代渐变脉冲加载动画样式 */
.loading-overlay {
  position: fixed;
  inset: 0;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.95), rgba(147, 51, 234, 0.95));
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(20px);
}

.modern-loading {
  text-align: center;
  color: white;
  max-width: 320px;
  width: 90%;
}

.loading-circle-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 2rem;
}

.loading-circle {
  width: 20px;
  height: 20px;
  background: linear-gradient(45deg, #ffffff, rgba(255, 255, 255, 0.6));
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.3);
}

.loading-circle:nth-child(1) {
  animation-delay: -0.32s;
}
.loading-circle:nth-child(2) {
  animation-delay: -0.16s;
}
.loading-circle:nth-child(3) {
  animation-delay: 0s;
}

@keyframes bounce {
  0%,
  80%,
  100% {
    transform: scale(0.8) translateY(0);
    opacity: 0.7;
  }
  40% {
    transform: scale(1.2) translateY(-15px);
    opacity: 1;
  }
}

.loading-text h3 {
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.loading-text p {
  font-size: 1rem;
  opacity: 0.9;
  margin-bottom: 2rem;
  text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
}

.loading-progress {
  width: 100%;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
  overflow: hidden;
  position: relative;
}

.loading-progress .progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #ffffff, rgba(255, 255, 255, 0.8), #ffffff);
  border-radius: 2px;
  transition: width 0.3s ease;
  box-shadow: 0 0 8px rgba(255, 255, 255, 0.6);
}

/* 选择模态框样式 */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.selection-modal {
  background: white;
  border-radius: 1rem;
  padding: 0;
  width: 90%;
  max-width: 900px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
}

.selection-modal .modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #f8fafc, #f1f5f9);
}

.selection-modal .modal-header h3 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #6b7280;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 0.25rem;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.selection-modal .modal-content {
  padding: 2rem;
  max-height: 50vh;
  overflow-y: auto;
}

.selection-step {
  margin-bottom: 2rem;
}

.selection-step h4 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.selection-step h4:before {
  content: '🎯';
  font-size: 1rem;
}

.selection-step p {
  color: #6b7280;
  margin-bottom: 1rem;
}

.nodes-selection {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-bottom: 1.5rem;
}

.node-option {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 0.75rem;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.node-option:hover {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.05);
}

.node-option.active {
  border-color: #3b82f6;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(6, 182, 212, 0.1) 100%);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.node-option-marker {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #e5e7eb, #d1d5db);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  color: #374151;
  flex-shrink: 0;
}

.node-option.active .node-option-marker {
  background: linear-gradient(135deg, #3b82f6, #06b6d4);
  color: white;
}

.node-option-content {
  flex: 1;
}

.node-option-content h5 {
  margin: 0 0 0.25rem 0;
  font-size: 1rem;
  font-weight: 600;
  color: #1f2937;
}

.node-option-content p {
  margin: 0 0 0.5rem 0;
  font-size: 0.875rem;
  color: #6b7280;
  line-height: 1.4;
}

.node-option-meta {
  display: flex;
  gap: 1rem;
  font-size: 0.75rem;
}

.node-option-meta .duration {
  color: #3b82f6;
  font-weight: 500;
}

.characters-selection {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1rem;
}

.character-option {
  display: flex;
  gap: 0.75rem;
  padding: 1rem;
  border: 2px solid #e5e7eb;
  border-radius: 0.75rem;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.character-option:hover {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.05);
}

.character-option.active {
  border-color: #3b82f6;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.1) 0%, rgba(6, 182, 212, 0.1) 100%);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.character-option-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e5e7eb;
  flex-shrink: 0;
}

.character-option.active .character-option-avatar {
  border-color: #3b82f6;
}

.character-option-info {
  flex: 1;
}

.character-option-info h5 {
  margin: 0 0 0.25rem 0;
  font-size: 1rem;
  font-weight: 600;
  color: #1f2937;
}

.character-option-info p {
  margin: 0 0 0.5rem 0;
  font-size: 0.875rem;
  color: #6b7280;
  line-height: 1.4;
}

.character-option-skills {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.skills-label {
  font-size: 0.75rem;
  color: #374151;
  font-weight: 500;
}

.skills-preview {
  display: flex;
  gap: 0.25rem;
  flex-wrap: wrap;
}

.skill-preview {
  background: rgba(147, 51, 234, 0.1);
  color: #8b5cf6;
  padding: 0.125rem 0.375rem;
  border-radius: 0.375rem;
  font-size: 0.625rem;
  font-weight: 500;
}

.more-skills {
  background: rgba(107, 114, 128, 0.1);
  color: #6b7280;
  padding: 0.125rem 0.375rem;
  border-radius: 0.375rem;
  font-size: 0.625rem;
  font-weight: 500;
}

/* 🔧 技能为空时的提示 */
.no-skills-hint {
  color: #9ca3af;
  font-size: 0.75rem;
  font-style: italic;
}

.modal-footer {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  padding: 1.5rem 2rem;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
}

/* 空状态样式 */
.empty-state {
  position: fixed;
  inset: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.95);
  z-index: 1000;
}

.empty-content {
  text-align: center;
  padding: 2rem;
  background: white;
  border-radius: 1rem;
  box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-content h3 {
  font-size: 1.5rem;
  color: #1f2937;
  margin-bottom: 0.5rem;
}

.empty-content p {
  color: #64748b;
  margin-bottom: 1.5rem;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .container {
    max-width: 95vw;
  }

  .banner-main {
    flex-direction: column;
    gap: 1rem;
  }

  .banner-info {
    max-width: 100%;
  }

  .banner-stats {
    justify-content: center;
  }

  .character-details-grid {
    grid-template-columns: 1fr;
  }

  .content-grid {
    grid-template-columns: 1fr;
  }

  .settings-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .theater-preview-app {
    padding: 1rem;
  }

  .top-nav {
    flex-direction: column;
    gap: 1rem;
  }

  .banner {
    min-height: 180px;
  }

  .banner-content {
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 1rem;
  }

  .theater-title {
    font-size: 1.5rem;
  }

  .theater-description {
    font-size: 0.9rem;
  }

  .meta-badges {
    justify-content: center;
  }

  .banner-actions {
    flex-direction: row;
    justify-content: center;
  }

  .content-tabs {
    overflow-x: auto;
  }

  .tab-panel {
    padding: 1rem;
  }

  .panel-header-compact {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.75rem;
  }

  .character-controls-compact {
    flex-direction: column;
    gap: 0.75rem;
    align-items: flex-start;
  }

  .character-main {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .character-actions-compact {
    flex-direction: column;
    align-items: stretch;
  }

  .secondary-actions {
    flex-direction: column;
    gap: 0.75rem;
  }

  .selection-modal {
    width: 95%;
    max-height: 85vh;
  }

  .characters-selection {
    grid-template-columns: 1fr;
  }

  .character-option {
    flex-direction: column;
    text-align: center;
  }

  .character-option-avatar {
    align-self: center;
  }
}

@media (max-width: 480px) {
  .banner-stats {
    flex-direction: column;
    gap: 0.75rem;
  }

  .stat-mini {
    padding: 0.5rem 0.75rem;
  }

  .content-grid {
    gap: 0.75rem;
  }

  .character-details-grid {
    gap: 0.75rem;
  }

  .character-indicators-compact {
    gap: 0.35rem;
  }

  .char-indicator-mini {
    width: 28px;
    height: 28px;
  }
}
</style>
